package com.tss.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.tss.mapper.StudentMapper;
import com.tss.pojo.Result;
import com.tss.pojo.Student;
import com.tss.pojo.StudentExample;
import com.tss.pojo.StudentExample.Criteria;
import com.tss.service.StudentService;
import com.tss.utils.BeanUtils;

@Service
public class StudentServiceImpl implements StudentService {
	
	@Autowired
	private StudentMapper studentMapper;

	@Override
	public Result addStudent(Student student) {
		Result result = new Result();
		if(student==null||student.getRealName()==null||student.getIdCardNum()==null){
			result.setErrorMessage("参数错误");
			return result;
		}
		if(findStudent(student)!=null){
			result.setErrorMessage("身份证已经注册！");
			return result;
		}
		student.setValidate(true);
		studentMapper.insert(student);
		result.setSuccessMessage("注册成功！");
		return result;
	}

	@Override
	public Result deleteStudent(Long id) {
		Result result = new Result();
		Student student = new Student();
		student.setId(id);
		student = findStudent(student);
		if(student==null){
			result.setErrorMessage("用户不存在");
			return result;
		}
		student.setValidate(false);
		updateStudent(student);
		result.setSuccessMessage("删除学员成功！");
		return result;
		
	}

	@Override
	public Result updateStudent(Student student) {
		Result result = new Result();
		if(student==null||student.getId()==null){
			result.setErrorMessage("参数错误！");
			return result;
		}
		Student s = findStudent(student);
		if(s==null){
			result.setErrorMessage("学员不存在！");
			return result;
		}
		s=BeanUtils.updateBean(s, student);
		studentMapper.updateByPrimaryKey(s);
		result.setSuccessMessage("修改成功");
		return result;
	}

	@Override
	public List<Student> listStudent(Student student) {
		StudentExample example = new StudentExample();
		Criteria criteria = example.createCriteria();
		criteria.andValidateEqualTo(true);
		
		List<Student> list = studentMapper.selectByExample(example);
		return list;
	}
	
	@Override
	public Student findStudent(Student student) {
		if(student==null){
			return null;
		}
		if(student.getId()!=null){
			return studentMapper.selectByPrimaryKey(student.getId());
		}
		StudentExample example = new StudentExample();
		Criteria criteria = example.createCriteria();
		criteria.andValidateEqualTo(true);
		criteria.andValidateEqualTo(true);
		if(student.getIdCardNum()!=null){
			criteria.andIdCardNumEqualTo(student.getIdCardNum());
			List<Student> list = studentMapper.selectByExample(example);
			if(!list.isEmpty()){
				return list.get(0);
			}
		}
		return null;
	}

	
	
	
	

}
